package cn.swpu.bose;


import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
import java.util.Collections;
import java.util.List;
import java.util.Objects;


/**
 * Created by 11616 on 2016/7/8.
 */
@Transactional
@SuppressWarnings("unchecked")
public class DaoSupportImpl<T>  implements DaoSupport<T> {
    @Resource
    protected SessionFactory sessionFactory;

    private Class<T> clazz;

    public DaoSupportImpl() {
        //使用反射技术得到T的真实类型
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();//获取当前new的对象的泛型的父类类型
        this.clazz = (Class<T>) pt.getActualTypeArguments()[0];//获取第一个类型参数的真实类型
        System.out.println(clazz);
    }

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void save(T entity) {
        getSession().save(entity);
    }

    @Override
    public void delete(Long id) {

        T obj =  findById(id);
        if(obj != null){
            getSession().delete(obj);
        }
    }

    @Override
   public void update(T entity){
        getSession().update(entity);
   }


    @Override
    public T findById(Long id) {
        if(id !=null) {
            return (T) getSession().get(clazz, id);
        }
        else return null;

    }

    @Override
    public List<T> findAll() {
        return getSession().createQuery(
                "from "+clazz.getSimpleName())
                .list();
    }

    @Override

    public List<T> getByIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return Collections.EMPTY_LIST;
        } else {
            return getSession().createQuery(//
                    "from " + clazz.getSimpleName() + " where id in(:ids)")//
                    .setParameterList("ids", ids)//
                    .list();
        }
    }


}
